package com.ktvme.taskInstance;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ktvme.core.AbstractOperator;
import com.ktvme.core.DolphinClientConstant;
import com.ktvme.core.DolphinException;
import com.ktvme.result.PageResult;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
public class TaskInstanceOperator extends AbstractOperator {

    public TaskInstanceOperator(String dolphinAddress, String token) {
        super(dolphinAddress, token);
    }

    /**
     * 分页查询任务实例
     *
     * @param projectCode 项目代码
     * @param page 页码
     * @param size 每页大小
     * @param processInstanceId 流程实例 ID
     * @param searchVal 搜索关键字
     * @param stateType 状态类型
     * @param startDate 开始时间 (格式: yyyy-MM-dd)
     * @param endDate 结束时间 (格式: yyyy-MM-dd)
     * @return 任务实例列表
     */
    public PageResult<TaskInstanceQueryResp> page(
            Long projectCode, 
            Integer page, 
            Integer size, 
            Long processInstanceId,
            String searchVal,
            String stateType,
            String startDate,
            String endDate
    ) {
        page = Optional.ofNullable(page).orElse(DolphinClientConstant.Page.DEFAULT_PAGE);
        size = Optional.ofNullable(size).orElse(DolphinClientConstant.Page.DEFAULT_SIZE);

        String url = baseUrl + "/projects/" + projectCode + "/task-instances";
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageNo", page);
        queryParams.put("pageSize", size);
        
        // 添加可选参数
        if (processInstanceId != null) {
            queryParams.put("processInstanceId", processInstanceId);
        }
        if (searchVal != null && !searchVal.trim().isEmpty()) {
            queryParams.put("searchVal", searchVal);
        }
        if (stateType != null && !stateType.trim().isEmpty()) {
            queryParams.put("stateType", stateType);
        }
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryParams.put("startDate", startDate);
        }
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryParams.put("endDate", endDate);
        }

        try {
            HttpResponse response = HttpRequest.get(url)
                    .header("token", token)
                    .form(queryParams)
                    .execute();

            if (response.isOk()) {
                JSONObject jsonResponse = JSONUtil.parseObj(response.body());
                JSONObject data = jsonResponse.getJSONObject("data");

                // 如果 "data" 为空或不存在，则直接返回空的结果
                if (data == null || data.isEmpty()) {
                    return new PageResult<>();
                }

                JSONArray totalList = data.getJSONArray("totalList");
                List<TaskInstanceQueryResp> records = JSONUtil.toList(totalList, TaskInstanceQueryResp.class);

                PageResult<TaskInstanceQueryResp> pageResult = new PageResult<>();
                pageResult.setRecords(records);
                pageResult.setCurrentPage(data.getInt("currentPage"));
                pageResult.setPageSize(data.getInt("pageSize"));
                pageResult.setTotalPages(data.getInt("totalPage"));
                pageResult.setTotalRecord(data.getLong("total"));

                return pageResult;
            } else {
                throw new IOException("HTTP request failed with status code: " + response.getStatus());
            }
        } catch (Exception e) {
            throw new DolphinException("分页查询任务实例失败", e);
        }
    }

    /**
     * 查询任务实例日志
     *
     * @param projectCode 项目代码
     * @param skipLineNum 跳过的行数
     * @param limit 最大返回行数
     * @param taskInstanceId 任务实例 ID
     * @return 日志内容字符串
     */
    public String queryLog(Long projectCode, Integer skipLineNum, Integer limit, Long taskInstanceId) {
        skipLineNum = Optional.ofNullable(skipLineNum).orElse(DolphinClientConstant.LogLimit.DEFAULT_SKIP);
        limit = Optional.ofNullable(limit).orElse(DolphinClientConstant.LogLimit.DEFAULT_LIMIT);

        String url = baseUrl + "/log/" + projectCode + "/detail";
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("projectCode", projectCode);
        queryParams.put("taskInstanceId", taskInstanceId);
        queryParams.put("skipLineNum", skipLineNum);
        queryParams.put("limit", limit);

        try {
            HttpResponse response = HttpRequest.get(url)
                    .header("token", token)
                    .form(queryParams)
                    .execute();

            if (response.isOk()) {
                JSONObject jsonResponse = JSONUtil.parseObj(response.body());
                return jsonResponse.getStr("data");
            } else {
                throw new IOException("HTTP request failed with status code: " + response.getStatus());
            }
        } catch (Exception e) {
            throw new DolphinException("查询任务实例日志失败", e);
        }
    }

    /**
     * 下载任务实例日志,最后n行
     *
     * @param projectCode 项目代码
     * @param taskInstanceId 任务实例 ID
     * @return 日志内容字符串
     */
    public String donwloadLog(Long projectCode, Long taskInstanceId,Integer lastLineNum){
        String url = baseUrl + "/log/" + projectCode + "/download-log";
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("projectCode", projectCode);
        queryParams.put("taskInstanceId", taskInstanceId);
        try {
            // 设置请求头中的 Authorization 字段
            HttpResponse response = HttpUtil.createGet(url)
                    .form(queryParams)
                    .header("token",token)
                    .execute();
            //根据lastlinenum获取最后几行数据
            if (lastLineNum != null) {
                String logContent = response.body();
                String[] lines = logContent.split("\n");
                int startIndex = Math.max(0, lines.length - lastLineNum);
                StringBuilder lastLines = new StringBuilder();
                for (int i = startIndex; i < lines.length; i++) {
                    lastLines.append(lines[i]).append("\n");
                }
                return lastLines.toString();
            } else {
                return response.body();
            }


        } catch (Exception e) {
            throw new DolphinException("下载日志失败", e);
        }
    }

}